#coding=utf-8
from time import sleep 
from stutils import set_django_environ
set_django_environ()

from stdj.stock.models import Share
from stscraper import NoPriceError
from deal import DealThread
import datetime
td = datetime.date.today().isoformat()

from stsettings import datadir 
LOGDIR = datadir + '/log'

def get_everyday_price(shares):
    
    for s in shares:
        print s
        try:
            s.tdprice2db()
            e = s.exday_today()
            p = e.price
            print p.end, p.change
            
        except NoPriceError,e:
            print e
            

import threading            
class EdPriceThread(threading.Thread):
    def __init__(self, id, shares, log=None):
        threading.Thread.__init__(self)
        self.id = id
        self.shares = shares
        if log:self.log = log
        else:
            self.log = LOGDIR + '%i.csv'%id
            
    def run(self):
        f = open(self.log, 'w')
        codes = [s.code for s in self.shares]
        '线程%'
        for s in self.shares:
            try:
                s.tdprice2db()
            except NoPriceError,e:
                pass
        
if __name__  == '__main__':
    from threading import Thread
    price_threads = []
    thread_num = 6
    
    shares = Share.objects.order_by('code')
    get_everyday_price(shares)
    '''
    step = shares.count()/thread_num + 1
    for i in range(thread_num):
        ss = shares[i*step: (i+1)*step]
        t = Thread(target=everyday_price, args=(ss,))
        price_threads.append(t)
        t.start()
        
    sleep(600)    
    while True:
        states = [t.isAlive() for t in price_threads]
        r = reduce(lambda x, y : x or y , states)
        #所有的线程都退出了: 
        if not r:
            break
        sleep(60)
    '''    
    sleep(10)
    
    print "Now, start to 下载每天成交明细." 
    step = shares.count()/thread_num + 1
    start_date = td
    for i in range(thread_num):
        ss = shares[i*step: (i+1)*step]
        DealThread(i, ss, start_date ).start()